<template>
  <view class="chat-window">
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="header-content">
        <view class="back-button" @click="goBack">
          <text class="back-icon">←</text>
        </view>
        <view class="user-info">
          <image 
            class="user-avatar" 
            :src="otherUser.avatar || defaultAvatar"
            mode="aspectFill"
          ></image>
          <text class="user-name">{{ otherUser.name }}</text>
        </view>
      </view>
    </view>

    <!-- 消息区域 -->
    <scroll-view 
      class="messages-container" 
      ref="messagesContainer"
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoViewId"
      scroll-y="true"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      :key="scrollViewKey"
      enable-back-to-top="true"
      enable-flex="true"
    >
      <view class="messages-list">
        <view 
          v-for="message in privateMessages" 
          :key="message.message_id"
          :class="getMessageItemClass(message)"
          :id="'message-' + message.message_id"
        >
          <image 
            v-if="message.sender_id !== currentUserId"
            class="avatar" 
            :src="otherUser.avatar || defaultAvatar"
            mode="aspectFill"
          ></image>
          <view class="message-content">
            <text class="message-text">{{ message.content }}</text>
            <text class="message-time">{{ formatTime(parseDate(message.createdAt), 'HH:mm:ss') }}</text>
          </view>
          <image 
            v-if="message.sender_id === currentUserId"
            class="avatar" 
            :src="currentUser.avatar || defaultAvatar"
            mode="aspectFill"
          ></image>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-container">
      <input 
        class="message-input" 
        v-model="inputMessage" 
        placeholder="输入消息..." 
        @confirm="sendMessage"
      />
      <button class="send-button" @click="sendMessage">发送</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import { getUserInfo, formatTime, parseDate, showToast } from '@/utils/index'
import { getPrivateMessageHistory } from '@/api/user/privateChat'
import { usePrivateChatStore } from '@/stores/privateChat'

// 使用项目中实际存在的默认头像
const defaultAvatar = '/static/logo.png'

// 定义属性
const props = defineProps({
  otherUser: {
    type: Object,
    required: true
  },
  chatId: {
    type: Number,
    default: null
  }
})

// 定义事件
const emit = defineEmits(['close'])

// 获取 Pinia store 实例
const privateChatStore = usePrivateChatStore()

// 当前用户信息
const currentUser = ref<any>({})
const currentUserId = ref<number>(0)

// 从 store 中获取私聊消息
const privateMessages = computed(() => {
  // 对消息按时间排序（升序，旧消息在前，新消息在后）
  const messages = [...privateChatStore.getPrivateMessages(props.chatId)].sort((a, b) => {
    // 使用更高效的排序方法，避免重复创建Date对象
    const timeA = new Date(parseDate(a.createdAt)).getTime()
    const timeB = new Date(parseDate(b.createdAt)).getTime()
    return timeA - timeB
  })

  return messages
})

// 输入的消息
const inputMessage = ref('')

// 消息容器引用
const messagesContainer = ref(null);

// 滚动位置
const scrollTop = ref(0);
const scrollHeight = ref(0);
const scrollViewKey = ref(Date.now()); // 使用时间戳确保唯一性
const scrollIntoViewId = ref(''); // 用于微信小程序的scrollIntoView

// 下拉刷新状态
const refreshing = ref(false);

// 当前页码
const currentPage = ref(1);

// 是否还有更多数据
const hasMore = ref(true);

// 获取消息项的类名
const getMessageItemClass = (message: any) => {
  const baseClass = 'message-item'
  const positionClass = message.sender_id === currentUserId.value ? 'sent' : 'received'
  return `${baseClass} ${positionClass}`
}

// 监听私聊消息变化，自动滚动到底部
watch(privateMessages, () => {
  scrollToBottom()
}, { deep: true })

// 发送消息
const sendMessage = () => {
  if (!inputMessage.value.trim()) {
    return
  }

  // 通过WebSocket发送消息
  const messageData = {
    receiverId: props.otherUser.user_id,
    content: inputMessage.value
  }

  privateChatStore.handlePrivateMessageSend(messageData)

  // 清空输入框
  inputMessage.value = ''
}

// 加载历史消息
const loadHistoryMessages = async () => {
  if (!props.chatId) return;
  
  try {
    const res: any = await getPrivateMessageHistory({ 
      chat_id: props.chatId,
      page: 1,
      limit: 20
    });
    
    if (res.code === 200) {
      // 使用 setPrivateMessages 替换整个聊天记录，避免重复
      privateChatStore.setPrivateMessages(props.chatId, res.data.messages);
      
      // 更新当前页码
      currentPage.value = 1;
      // 检查是否还有更多数据
      hasMore.value = res.data.messages.length >= 20;
      // 滚动到底部
      nextTick(() => {
        // 延迟一小段时间确保DOM更新完成
        setTimeout(() => {
          scrollToBottom();
        }, 100);
      });
    }
  } catch (error) {
    console.error('获取聊天记录异常:', error);
  }
}

// 加载更多消息
const loadMoreMessages = async () => {
  // 如果没有更多数据，直接返回
  if (!hasMore.value) {
    showToast('没有更多消息了');
    return;
  }
  
  try {
    const res: any = await getPrivateMessageHistory({
      chat_id: props.chatId,
      page: currentPage.value + 1,
      limit: 20
    });
    
    if (res.code === 200) {
      // 检查是否还有更多数据
      hasMore.value = res.data.messages.length >= 20;
      
      // 如果有新数据，将新消息添加到 store (带去重)
      if (res.data.messages.length > 0) {
        res.data.messages.forEach((message: any) => {
          privateChatStore.addPrivateMessageUnique(props.chatId, message);
        });
        
        // 更新当前页码
        currentPage.value += 1;
        
        showToast('加载更多消息成功');
      } else {
        showToast('没有更多消息了');
      }
    }
  } catch (error) {
    console.error('加载更多消息异常:', error);
  }
}

// 下拉刷新
const onRefresh = async () => {
  if (refreshing.value) return;
  refreshing.value = true;
  
  // 模拟加载更多历史消息
  await loadMoreMessages();
  
  // 停止下拉刷新
  refreshing.value = false;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    // #ifdef MP-WEIXIN
    // 微信小程序使用 scroll-into-view 滚动到最后一条消息
    setTimeout(() => {
      if (privateMessages.value.length > 0) {
        const lastMessage = privateMessages.value[privateMessages.value.length - 1];
        scrollIntoViewId.value = 'message-' + lastMessage.message_id;
        
        // 更新scrollViewKey确保唯一性
        scrollViewKey.value = Date.now();
      }
    }, 50);
    // #endif
    
    // #ifndef MP-WEIXIN
    // H5和其他平台保持原有逻辑
    const query = uni.createSelectorQuery();
    query.select('.messages-list').boundingClientRect((listRect) => {
      if (listRect) {
        // 通过增加scrollTop的值确保触发滚动
        scrollTop.value = listRect.height + 1000;
      }
    }).exec();
    // #endif
  });
}

// 处理已读消息
const handleMarkAsRead = () => {
  privateChatStore.markPrivateChatAsRead(props.chatId)
}

// 返回上一页
const goBack = () => {
  handleMarkAsRead()
  emit('close')
}

// 初始化组件
onMounted(() => {
  // 获取当前用户信息
  const userInfo = getUserInfo()
  if (userInfo) {
    currentUser.value = userInfo
    currentUserId.value = userInfo.user_id
  }

  // 如果有chatId，加载历史消息
  if (props.chatId) {
    loadHistoryMessages()
  }

  handleMarkAsRead()
})

</script>

<style scoped>
.chat-window {
  display: flex;
  flex-direction: column;
  height: 80vh;
  width: 90vw;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  overflow: hidden;
}

.chat-header {
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  z-index: 100;
  flex-shrink: 0;
}

.header-content {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 20rpx;
}

.back-icon {
  font-size: 36rpx;
  color: #007aff;
}

.user-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 15rpx;
}

.user-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.messages-container {
  flex: 1;
  padding: 20rpx;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.messages-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.message-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: flex-end;
  width: 100%;
}

.message-item.received {
  justify-content: flex-start;
}

.message-item.sent {
  justify-content: flex-end;
}

.avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin: 0 15rpx;
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  display: flex;
  flex-direction: column;
}

.message-text {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  word-wrap: break-word;
}

.message-item.sent .message-text {
  background-color: #007aff;
  color: #fff;
}

.message-time {
  font-size: 20rpx;
  color: #999;
  margin-top: 10rpx;
  align-self: flex-end;
}

.input-container {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  border-top: 1rpx solid #eee;
  flex-shrink: 0;
}

.message-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  font-size: 28rpx;
  align-self: center;
}

.send-button {
  width: 120rpx;
  height: 70rpx;
  margin-left: 20rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 10rpx;
  font-size: 28rpx;
}
</style>